package com.blb.ssh.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.blb.ssh.entity.User;
import com.blb.ssh.service.UserService;

@Controller
@Scope("prototype")
public class IndexAction extends BaseAction	{

	private static final long serialVersionUID = -336008223141119489L;

	private User user;
	
	@Autowired
	private UserService userService;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * 跳转到登录页面
	 * @return
	 */
	@Action(value = "", results = {
		@Result(name = PAGE_LOGIN, location = "/login.jsp")
	})
	public String index(){
		System.out.println("login page...");
		return PAGE_LOGIN;
	}
	
	/**
	 * 登录
	 * @return
	 */
	@Action(value = "/login", results = {
		@Result(name = SUCCESS, location = "/WEB-INF/jsp/index.jsp"),
		@Result(name = ERROR, location = "/login.jsp")
	})
	public String login(){
		HttpServletRequest request = ServletActionContext.getRequest();
		try{
			if (user==null || "".equals(user.getUsername())) {
				throw new Exception("用户密码不能为空");
			}
			userService.login(user.getUsername(), user.getPassword());
			request.getSession().setAttribute("user", user);
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute("msg", e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
}
